import DataSelect from '@/components/DataSelect';
import { CascaderSelect } from '@alifd/next';
import { CascaderSelectProps } from '@alifd/next/types/cascader-select';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { getCities, getStations } from './api';


interface IShuttleStationSelect extends CascaderSelectProps {
  stationOnly?: boolean;
  cityId?: string;
}
function ScStationSelect({ stationOnly = false, cityId, ...props }: IShuttleStationSelect ) {
  return stationOnly === true
    ? <DataSelect args={{ cityId}} onFetch={cityId ? (n, args) => getStations(args.cityId) : () => []} labelField="name" valueField="id" {...props} />
    // ? <DataSelect args={args} onFetch={cityId ? (n, args) => getStations(args.cityId) : () => []} labelField="name" valueField="id" {...props} />
    : <ScStationSelectCascade {...props} />;
}

function ScStationSelectCascade({ ...props }: IShuttleStationSelect) {
  const [data, setData] = useState([]);
  const cities = useRef({}).current;

  useEffect(() => {
    (async function fetchData() {
      const items = await getCities();
      setData(items.map(mapper));
    })();
  }, []);

  const mapper = useCallback((v) => {
    const isStation = !!v.city;
    const label = isStation ? v.name : v.name;
    const value = isStation ? v.id : v.itemId;
    const item = {
      label,
      value,
      isLeaf: isStation,
      ...v,
    };
    if (!isStation) cities[value] = item;
    return item;
  }, []);

  const onLoadData = async (v) => {
    const item = cities[v.value];
    if (item.children) return;
    const children = await getStations(v.value);
    item.children = children.map(mapper);
    setData((prev) => [...prev]);
  };

  return (
    <CascaderSelect
      hasClear
      dataSource={data}
      loadData={onLoadData}
      // style={{ width: '100%' }}
      {...props}
    />
  );
}

export default ScStationSelect;
